package com.xiaocg.sparse.array;

/**
 * 二维数组 转 稀疏数组 再转二维数组
 */
public class SparseArray {
    public static void main(String[] args) {
        int[][] arrays = new int[9][9];
        arrays[1][2] = 1;
        arrays[1][3] = 2;
        arrays[2][4] = 1;
        arrays[5][7] = 2;

        for (int[] row: arrays){
            for (int item: row){
                System.out.printf("%d\t",item);
            }
            System.out.println();
        }

        int sum =0;
        for (int i=0;i<9;i++){
            for (int j=0;j<9;j++) {
                if (arrays[i][j]!=0){
                    sum++;
                }
            }
        }

        int[][] sparseArrays = new int[sum+1][3];
        sparseArrays[0][0] = 9;
        sparseArrays[0][1] = 9;
        sparseArrays[0][2] = sum;

        int count = 0;
        for (int i=0;i<9;i++){
            for (int j=0;j<9;j++) {
                if (arrays[i][j]!=0){
                    count++;
                    sparseArrays[count][0] = i;
                    sparseArrays[count][1] = j;
                    sparseArrays[count][2] = arrays[i][j];
                }
            }
        }

        System.out.println("稀疏数组");

        for (int[] row: sparseArrays){
            for (int item: row){
                System.out.printf("%d\t",item);
            }
            System.out.println();
        }

        int[][] arrays2 = new int[sparseArrays[0][0]][sparseArrays[0][1]];
        for (int i=1;i< sparseArrays.length;i++){
            arrays2[sparseArrays[i][0]][sparseArrays[i][1]] =sparseArrays[i][2];
        }

        System.out.println("二维数组 ");
        for (int[] row: arrays2){
            for (int item: row){
                System.out.printf("%d\t",item);
            }
            System.out.println();
        }

    }
}
